import { reactive, ref, watch } from 'vue';
// import { uni } from '@dcloudio/uni-app';
import { request } from '@/utils/request'
import { tokenManager } from '@/utils/tokenManager';

// const token = 'pat_hDLUMqRTuu6iyZo25QTCKqK07KkRwh6JiQiroJZSUqdKlDnwrMF6PE1LI5POPB70'; //2025/3/1过期
// const workflow_id = '7466775571867959346';
// const url = `https://api.coze.cn/v1/workflow/run`;
// const headers = {
//     'Content-Type': 'application/json',
//     'Authorization': `Bearer ${token}`,
// };

export function useSongGenerator(popup, imgPopup, songPopup) {
    const workflow_word_id = '7466775571867959346';
    const workflow_img_id = '7466274557663789067';
    

    const list = ref([]);
    const currentTab = ref(0);
    const sections = reactive([
        { name: 'word', label: '歌词', show: true },
        { name: 'desc', label: '描述', show: true },
        // { name: 'img', label: '图片', show: true },
    ]);

    const editContent = ref('');
    const currentEdit = ref({ section: '', index: -1 });


    const formData = reactive(initFormData());
    console.log('formData', formData);
    const curImgIndex = ref(0);
    const songFormData = reactive({
        name: '',
        description: ''
    });

    const imgFormData = reactive({
        content: '',
        count: 2,
        scene: ''
    });

    function initFormData() {
        try {
            const savedData = uni.getStorageSync('cozeFormData');
            if (savedData) {
                return JSON.parse(savedData);
            }
        } catch (e) {
            console.error('读取本地数据失败:', e);
        }
        return { count: '', content: '' };
    }

    function saveFormData() {
        try {
            uni.setStorageSync('cozeFormData', JSON.stringify(formData));
        } catch (e) {
            console.error('保存数据失败:', e);
        }
    }

    async function loadImg() {
        try {
            const body = {
                parameters: {
                    desc: imgFormData.content,
                    total: Number(imgFormData.count),
                    scene: imgFormData.scene
                },
                workflow_id: workflow_img_id,
                is_async: false,
            };

            const response = await uni.request({
                url: tokenManager.getCozeApiUrl(),
                method: 'POST',
                header: tokenManager.getHeaders(),
                data: body,
            });

            if (response.statusCode !== 200) {
                throw new Error(`HTTP error! status: ${response.statusCode}`);
            }

            const obj = response.data;

            console.log('obj', obj);
            const aim = JSON.parse(obj.data)

            list.value[currentTab.value]['imgs'][curImgIndex.value].push(...aim.output)
            console.log('list', list.value[currentTab.value]['imgs'])

        } catch (error) {
            console.error('Error:', error);
            uni.showToast({ title: '请求失败', icon: 'none' });
        }
    }

    async function loadData() {
        try {
            const body = {
                parameters: { input: formData.content },
                workflow_id: workflow_word_id,
                is_async: false,
            };

            const response = await uni.request({
                url: tokenManager.getCozeApiUrl(),
                method: 'POST',
                header: tokenManager.getHeaders(),
                data: body,
            });

            if (response.statusCode !== 200) {
                throw new Error(`HTTP error! status: ${response.statusCode}`);
            }

            const obj = response.data;
            const aim = JSON.parse(obj.data);

            list.value.push({
                word: aim.word,
                desc: aim.desc.map((item, i) => `${item} (${aim.scene[i]} | ${aim.duration[i]})`),
                imgs: aim.desc.map((_) => [])
            });

            console.log('list:', list.value);

        } catch (error) {
            console.error('Error:', error);
            uni.showToast({ title: '请求失败', icon: 'none' });
        }
    }

    async function onSong() {
        const count = Number(formData.count);
        if (count > 0) {
            saveFormData();
            for (let i = 0; i < count; i++) {
                setTimeout(() => loadData(), i * 2000);
            }
        } else {
            uni.showToast({ title: '请输入大于0的数字', icon: 'none' });
        }
    }

    function showEdit(section, index) {
        console.log(section, index);
        currentEdit.value = { section, index };
        editContent.value = list.value[currentTab.value][section][index];
        if (popup.value && popup.value.open) { // 确保 popup 和 open 方法存在
            popup.value.open();
        } else {
            console.error('popup 未正确初始化或没有 open 方法');
        }
    }

    function showImg(section, index) {
        curImgIndex.value = index;
        const str = list.value[currentTab.value]['desc'][index];
        const ary = str.split(" (");
        imgFormData.content = ary[0];
        imgFormData.scene = ary[1].split(" |")[0]

        if (imgPopup.value && imgPopup.value.open) { // 确保 popup 和 open 方法存在
            imgPopup.value.open();
        } else {
            console.error('imgPopup 未正确初始化或没有 open 方法');
        }
    }

    function hideEdit() {
        if (popup.value && popup.value.close) { // 确保 popup 和 close 方法存在
            popup.value.close();
        } else {
            console.error('popup 未正确初始化或没有 close 方法');
        }
        editContent.value = '';
        currentEdit.value = { section: '', index: -1 };
    }

    function confirmEdit() {
        const { section, index } = currentEdit.value;
        if (section && index > -1) {
            list.value[currentTab.value][section][index] = editContent.value;
        }
        hideEdit();
    }

    // watch(() => list.value.length, (newLength) => {
    //     if (newLength > 0) {
    //         currentTab.value = newLength - 1;
    //     }
    // });

    async function saveSongInfo() {
        console.log('songFormData', songFormData);
        songPopup.value.close();

        const cur = list.value[currentTab.value];
        console.log("onSaveSong", cur, formData)
        const scenes = cur.desc.map((item, i)=>{
            return {
                name: `场景${i+1}`,
                description: item,
                images: cur.imgs[i],
                videos: []
            }
        })

        // return;
        const song = {
            name: songFormData.name,
            lyrics: list.value[currentTab.value].word,
            mp3: null,
            description: songFormData.description,
            scenes
        };

        try {
            const response = await request.post('/songs', song);
            console.log('歌曲保存成功:', response.data);
            // 在这里处理保存成功后的逻辑，例如重定向到歌曲列表页面
        } catch (error) {
            console.error('歌曲保存失败:', error);
            // 在这里处理保存失败后的逻辑，例如显示错误信息
        }
    }

    async function onSaveSong() {

        songPopup.value.open();
       
    }

    return {
        currentTab,
        formData,
        list,
        sections,
        showEdit,
        hideEdit,
        confirmEdit,
        editContent,
        onSong,
        imgFormData,
        showImg,
        loadImg,
        onSaveSong,
        songFormData,
        saveSongInfo
    };
}